package be.gnx.logging4eclipse.log4j;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

import org.apache.log4j.spi.LoggingEvent;

public class AcceptedSocket implements Runnable {

  private final Socket socket;

  private final Log4JListener log4JListener;

  protected AcceptedSocket(Socket socket, Log4JListener log4JListener) {
    this.socket = socket;
    this.log4JListener = log4JListener;
  }

  public void run() {
    try {
      final ObjectInputStream objectInputStream = new ObjectInputStream(socket
          .getInputStream());

      while (true) {
        if (log4JListener.isClosed()) {
          break;
        }
        log4JListener.receivedLoggingEvent((LoggingEvent) objectInputStream.readObject(),
            socket.getInetAddress().toString());
      }
    } catch (Exception ioException) {
      if (!socket.isClosed()) {
        System.err.println(ioException);
      }
    } finally {
      try {
        socket.close();
      } catch (IOException ioException) {
        if (!log4JListener.isClosed()) {
          System.err.println(ioException);
        }
      }
    }
  }

}
